#!/usr/bin/env -S node -r ./livescript-transform-implicit-async/register
require! {
  \fs-extra : fs
}
require! <[
  path
]>

sitemap = (host, url-date)~>
  li = []
  for [url,date] in url-date
    li.push "<url><loc>#host/#url</loc><lastmod>#date</lastmod></url>"
  """<?xml version="1.0" encoding="utf-8"?>
<urlset>#{li.join('')}</urlset>"""


module.exports = (dir, url-dict)!~>
  host = (await fs.readFile(
    path.join dir, \6du/host.txt
    \utf-8
  )).trim!

  url-date = [
    ["",new Date().toISOString().slice(0,10)]
  ]
  for k, li of url-dict
    for i in li
      {mtimeMs} = (await fs.stat(path.join(
        dir, k, i+"."+k
      )))
      url-date.push [i, new Date(mtimeMs).toISOString!.slice(0,10)]

  url-date.sort (a, b)!~>
    if a[1] > b[1]
      return 1
    return -1

  await fs.outputFile(
    path.join(dir, "sitemap.xml")
    sitemap(host, url-date)
  )

  robots = path.join dir, \robots.txt
  if not await fs.exists robots
    await fs.outputFile(
      robots
      """Sitemap: #host/sitemap.xml
User-agent: *
Disallow:
"""
    )
